package cn.fancy.sdk.login.utils;

import android.util.Log;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.crash.QCCrashLogPrint;
import cn.fancy.sdk.entity.GuildBaseInfo;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public class HttpReq {
    
    //繁星sdk
    //public static final String gregistertest = "http://129.204.237.52/api/sdk";	//测试环境
    //private static final String gregister = "https://game.fanxingol.com";	//正式环境
    
    //霸游
    //更换请求头时，还要把悬浮球图标 ic_float 换成 ic_float_2
    //private static final String gregister = "https://www.bayousy.com";	//正式环境
    
    //呆喵
    //private static final String gregister = "http://game.daimiaohudong.cn";    //正式环境
    
    
    // 把Map的data数据转成json
    private static String maptojson(Map<String, String> inputMap) {
        Gson gson = new Gson();
        String gsonstr = gson.toJson(inputMap);
        String gsontemp = gsonstr.replaceAll("\\\\", "");
        
        Log.d("gsontojson", "gsontojson" + gsontemp);
        
        String jsondeldata = gsontemp.substring(9);
        
        String[] gsonsplit = jsondeldata.split("\\}\"");
        
        return "{\"data\":" + gsonsplit[0] + "}" + gsonsplit[1];
    }
    
    public static String doGuildRequest(Map<String, String> mappp) {
        if (mappp == null) {
            Log.i("doGuildRequest", "str is null");
            return "";
        }
        String metaUrl = GuildBaseInfo.getInstance().getMetaUrl("API_URL");
        String reqUrl = metaUrl + "/api/sdk";
        String rsp = "";
        
        Map<String, String> infoMap = new HashMap<>();
        infoMap.put("url", reqUrl);
        infoMap.put("in", mappp.toString());
        
        String gsontemp = maptojson(mappp);
        Log.e("guiderequest", "guiderequest:" + gsontemp);
        try {
            rsp = gRequest(reqUrl, gsontemp);
            checkJson(rsp);
            infoMap.put("result", rsp);
            Log.i("doUploadLogRequest", infoMap + ",gsontemp:"+gsontemp);
            QCCrashLogPrint.getInstance().printCrux(infoMap.toString());
        } catch (Exception e) {
            e.printStackTrace();
            infoMap.put("result", rsp);
            infoMap.put("exception", e.toString());
            Log.e("doUploadLogRequest", infoMap.toString());
        }
        return rsp;
    }
    
    public static String gRequest(String getUrl, String buffer)
        throws Exception {
        HttpURLConnection httpConn = null;
        String ret ="";
        try {
            
            URL url = new URL(getUrl);
            
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(30 * 1000);
            httpConn.setReadTimeout(30 * 1000);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
            
            Logger.e("doRoleMessageRequest","=============" + buffer);
            
            byte[] b = buffer.getBytes();
            
            OutputStream os = httpConn.getOutputStream();
            os.write(b);
            os.flush();
            os.close();
            
            int statusCode = httpConn.getResponseCode();
            if (statusCode == 200) {
                InputStream is = httpConn.getInputStream();
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "utf-8"));
                
                String line;
                StringBuffer reBuf = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    
                    reBuf.append(line);
                    
                }
                ret = reBuf.toString();
                reader.close();
                is.close();
                
            } else {
                throw new Exception("Error occur when try to visit the url:"
                    + url.getPath() + " using HttpURLConnection");
                
            }
            
        } catch (Exception ex) {
            throw new Exception("Error occur execute "
                + "HttpRemoteProxy.performImpl(), the caused by " + ex);
        } finally {
            if (httpConn != null)
                httpConn.disconnect();
        }
        return ret;
    }
    
    public static String doFloatWebRequest(Map<String, String> str) {
        if (str == null) {
            Log.i("doFloatWebRequest", "str is null");
            return "";
        }
        StringBuilder headurl = new StringBuilder();
        headurl.append(GuildBaseInfo.getInstance().getMetaUrl("API_URL"));
        headurl.append("/mobile/float");
        headurl.append("?");
        
        Iterator iterator = str.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            headurl.append(entry.getKey());
            headurl.append("=");
            headurl.append(entry.getValue());
            headurl.append("&");
        }
        String urll = headurl.substring(0, headurl.length() - 1);    //delete the last sign &
        Log.e("doFloatWebRequest:", "doFloatWebRequest:" + urll);
        return urll;
    }
    
    private static void checkJson(String rsp) {
        try {
            new JSONObject(rsp);
        } catch (JSONException e) {
            Log.e("JSONException", e.toString());
        }
    }
}
